package com.zline.foodraise.ui.fragment;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.ProductViewPageRecycleAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.ProductBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.ui.activity.ProductDetailActivity_;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.MyLinearLayoutManager;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created by heshantao on 15/12/4.
 * 商品
 */
@EFragment(R.layout.me_viewpage)
public class ProductFragment extends Fragment implements RecyclerItemClicked {
    private static final String LOG_TAG = ProductFragment.class.getSimpleName();
    @ViewById(R.id.me_viewpage_recyclerView)
    RecyclerView recyclerView;
    @Bean
    ProductViewPageRecycleAdapter recycleAdapter;
    SparseArray<ProductBean> sparseArray;
    Context cxt;
    MyLinearLayoutManager layoutManager;
    @FragmentArg
    long userId;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    @Pref
    AppPref_ appPref;

    @ViewById(R.id.viewpage_exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.viewpage_ex_no_data_rl)
    RelativeLayout no_data_rl;
    @Bean
    NetworkUtil networkUtil;
    boolean loadMore = false;
    //当前fragment是否对用户可见
    boolean isVisibleToUser;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser=isVisibleToUser;
        /*if (isVisibleToUser) {
            loadData();
        }*/
        LUtil.i(LOG_TAG,"______setUserVisibleHint_______"+isVisibleToUser);
    }


    @AfterViews
    void doSomeAfterView(){
        LUtil.i(LOG_TAG, "______doSomeAfterView_______"+userId);
        cxt = getActivity();
        loadData();
        /*if (isVisibleToUser) {
            loadData();
        }*/
    }

    @Override
    public void onResume() {
        super.onResume();
        LUtil.i(LOG_TAG, "______onResume_______");
    }

    public void loadData() {
        sparseArray = new SparseArray<ProductBean>();
        if (networkUtil.isNetworkAvailable()) {
            requestProductListForUser();
        } else {
            TUtil.showShort(cxt, R.string.no_network);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            exception_fl.setVisibility(View.VISIBLE);
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            no_data_rl.setVisibility(View.GONE);
        }
    }


    //请求商品列表
    void requestProductListForUser() {
        httpOperator.requestProductListForUser(httpUtil, userId, Constant.PAGE_ROWS_NUMBER,
                currt_page, requestProductListHandler);
    }

    //获取用户商品列表回调
    AsyncHttpResponseHandler requestProductListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestProductListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        sparseArray = httpDataParsing.getUserProductList(response);
                        getPageCount(response);
                        if (loadMore) {
                            loadMore(sparseArray);
                        } else {
                            initRecyclerView();
                        }
                    } else {
                        loadMore=false;
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            loadMore=false;
        }
    };


    //加载更多
    void loadMore(SparseArray<ProductBean> productBeanSparseArray) {
        LUtil.i(LOG_TAG, "____loadMore_________" + recycleAdapter.getArrys().size());
        if (currt_page == pageCount) {
            recycleAdapter.setFootEnable(false);
            recycleAdapter.notifyItemChanged(recycleAdapter.getArrys().size());
        }
        recycleAdapter.addAll(productBeanSparseArray);
        loadMore=false;
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = recycleAdapter.getArrys().size();
        if (size == 0) {
            showNoDataView(true);
        } else {
            showNoDataView(false);
        }
    }


    //分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.PRODUCT_BEAN_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    void initRecyclerView() {
        recyclerView.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        layoutManager = new MyLinearLayoutManager(cxt);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recycleAdapter.setAdapterData(sparseArray);
        recycleAdapter.setRecycleItemClickListener(this);
        recyclerView.setAdapter(recycleAdapter);
        recyclerView.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        recycleAdapter.setFootEnable(true);
                        recycleAdapter.notifyItemChanged(recycleAdapter.getArrys().size());
                        requestProductListForUser();
                        loadMore = true;
                    }else {
                        TUtil.showShort(cxt, R.string.no_network);
                    }
                }

            }
        });

        isNoDataException();
    }

    //跳转商品详细页
    @Override
    public void onRecyclerItemClicked(int position) {
        LUtil.i(LOG_TAG, "________position_________" + position);
        ProductBean productBean = recycleAdapter.getArrys().get(position);
        if (productBean != null) {
            long productId = productBean.getProductId();
            String title = productBean.getProductName();
            try {
                title = java.net.URLEncoder.encode(title, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String url = appPref.rootUrl().get() + Constant.PRODUCT_DETAILE_URL + "?productId=" + productId +
                    "&title=" + title + "&isEmbed=1";
            ProductDetailActivity_.intent(cxt).url(url).title(productBean.getProductName()).start();
        }
    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {

    }
}
